#!/usr/bin/env sh

APP="server.py"
ports=(8001)

CURR_DIR=$(
  cd $(dirname $0)
  pwd
)

if [[ ! -d "$CURR_DIR/log" ]]; then
  mkdir "$CURR_DIR/log"
fi

function foo() {
  nohup python3 $CURR_DIR/servers/server.py --port=${ports[$i]} --app=mall_${ports[$i]}.log 2>>$CURR_DIR/log/err.log 1>>/dev/null &
}

function stop() {
  for i in ${ports[*]} ; do
    ps -ef | grep python | grep $APP | grep $i | grep -v grep | awk '{system("kill -9 "$2)}'
  done
}

function status() {
  count=0
  for ((i = 0; i < ${#ports[@]}; i++)); do
    ((count=count+`ps -ef | grep python | grep $APP | grep ${ports[$i]} | grep -v grep | wc -l`))
  done

  echo servers:$count
  if [ "$count" -ne ${#ports[@]} ]; then
    echo "servers have down.."
  else
    echo "server is running.."
  fi
}

function start() {
  echo "starting server...."
  for ((i = 0; i < ${#ports[@]}; i++)); do
    foo $i
  done
  sleep 1
  status
}

usage() {
  echo "usage: ./server_control.sh [start|stop|status]"
}

if [ $# -eq 1 ]; then
  if [ $1x == "start"x ]; then
    start
  elif [ $1x == "stop"x ]; then
    stop
  elif [ $1x == "status"x ]; then
    status
  else
    usage
  fi
elif [ $# -eq 2 ]; then
  # shellcheck disable=SC2039
  if [[ "$1"x == "start"x && "$2"x == "celery"x ]]; then
    echo "start celery"
    nohup celery -A servers.celery_server worker -l INFO &
  fi
fi
